﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Text;
using QuanLiSinhVien_v01.BUS.Data;
using QuanLiSinhVien_v01.DTO;

namespace QuanLiSinhVien_v01.BUS.Pattern
{
    class ObserverMailSender: Observer
    {
        public BangDiemDto BangDiem { get; set; }
        public override object DTO
        {
            get
            {
                return BangDiem;
            }
            set
            {
                BangDiem = (BangDiemDto)value;
            }
        }
        public ObserverMailSender()
        {
            BangDiemBus.Observers.Add(this);
        }

        public void SendMail(string toMail, string toName)
        {
            SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
            var fromAddress = new MailAddress(smtpSection.Network.UserName, "Nhóm Quý Kỳ");
            var toAddress = new MailAddress(toMail, toName);
            string fromPassword = smtpSection.Network.Password;
            string subject = "Đồ án Kiến trúc PM";
            string body = "Điểm của bạn ở môn" + BangDiem.MaMonHoc + " đã được thay đổi.\n" ;
            body += " Lí thuyết: " + BangDiem.DiemLiThuyet + "\n";
            body += " Thực hành: " + BangDiem.DiemThucHanh + "\n";
            body += " Điểm khác: " + BangDiem.DiemKhac + "\n";
            body += " Tổng kết: " + BangDiem.DiemTongKet + "\n";


            var smtp = new SmtpClient();
            {
                smtp.Host = smtpSection.Network.Host;
                smtp.Port = smtpSection.Network.Port;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);
                smtp.Timeout = 20000;
            }

            using (var message = new MailMessage(fromAddress, toAddress))
            {
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true;
                smtp.Send(message);
            }
            
        }

        override public void Update()
        {
            SinhVienBus sinhVienBus = new SinhVienBus();
            sinhVienBus.Info.MSSV = BangDiem.MSSV;
            SinhVienDto sinhVien = sinhVienBus.GetSinhVien();
            SendMail(sinhVien.Email, sinhVien.HoTen);
        }
    }
}
